package com.example.springboot.controller.api;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.springboot.common.Result;
import com.example.springboot.entity.Favorites;
import com.example.springboot.entity.Homestays;
import com.example.springboot.mapper.FacilitiesMapper;
import com.example.springboot.mapper.FavoritesMapper;
import com.example.springboot.service.IFavoritesService;
import com.example.springboot.service.IHomestaysService;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 民宿收藏表 API控制器 - 专门用于不需要token验证的API
 * </p>
 *
 * @author
 */
@RestController
@RequestMapping("/api/favorites")
public class FavoritesApi {

    @Resource
    private IFavoritesService iFavoritesService;

    @Resource
    private IHomestaysService iHomestaysService;

    @Resource
    private FavoritesMapper favoritesMapper;

    //个人主页收藏列表
    @GetMapping("/page")
    public Result findFavoriteHomestays(@RequestParam String userId,
                                        @RequestParam Integer page,
                                        @RequestParam Integer pageSize) {

        // 1. 先分页查询收藏表获取民宿ID列表
        QueryWrapper<Favorites> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("homestay_id");
        queryWrapper.eq("user_id", userId);
        queryWrapper.orderByDesc("time"); // 按收藏时间倒序

        Page<Favorites> favoritesPage = iFavoritesService.page(new Page<>(page, pageSize), queryWrapper);

        // 如果没有收藏记录，直接返回空分页
        if (favoritesPage.getRecords().isEmpty()) {
            return Result.success(favoritesPage);
        }

        // 2. 提取民宿ID列表
        List<Integer> homestayIds = favoritesPage.getRecords()
                .stream()
                .map(Favorites::getHomestayId)
                .collect(Collectors.toList());

        // 3. 根据ID列表查询民宿详细信息
        List<Homestays> homestays = iHomestaysService.listByIds(homestayIds);

        // 4. 保持原始分页信息但替换为民宿数据
        Page<Homestays> resultPage = new Page<>(
                favoritesPage.getCurrent(),
                favoritesPage.getSize(),
                favoritesPage.getTotal()
        );
        //将查询到的民宿详细信息列表 homestays 设置为分页对象的记录内容。
        resultPage.setRecords(homestays);
        return Result.success(resultPage);
    }

    //删除收藏
    @DeleteMapping("/{id}")
    public Result delete(@PathVariable Integer id){
        favoritesMapper.deleteById(id);
        return Result.success();
    }

    // 删除对应收藏
    @PostMapping("/unCol")
    public Result deleteLikes(@RequestBody Favorites favorites) {
        favoritesMapper.deleteisLikesById(favorites.getHomestayId(), favorites.getUserId());
        return Result.success();
    }


    // 新增或者更新
    @PostMapping("/add")
    public Result save(@RequestBody Favorites favorites) {
        iFavoritesService.saveOrUpdate(favorites);
        return Result.success();
    }

    //是否收藏
    @PostMapping("/isCol")
    public Result isCol(@RequestBody Favorites favorites) {
        // 参数校验
        if (favorites.getHomestayId() == null || favorites.getUserId() == null) {
            return Result.error("500","民宿ID和用户ID不能为空");
        }

        try {
            // 查询收藏记录
            Integer count = favoritesMapper.selectisLikes(favorites.getHomestayId() , favorites.getUserId());

            // 返回结果
            // 假设 selectisLikes 返回的是记录数(0表示未点赞，1表示已点赞)
            boolean isLiked = count != null && count > 0;

            return Result.success(isLiked);

        } catch (Exception e) {
            return Result.error("500","点赞过了");
        }
    }

}
